package com.hundsun.yr.universal.p2p.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.Utils.HeaderMap;
import com.hundsun.yr.universal.library.adapter.HolderAdapter;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSNoScrollListView;
import com.hundsun.yr.universal.library.widget.HSSwipeRefreshLayout;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.AuthListBean;
import com.hundsun.yr.universal.p2p.bean.LoanProductBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.bean.enums.EnumProtocol;
import com.hundsun.yr.universal.p2p.config.Config.SPPath;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.datahandler.LoanHandler;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.IWantLoanActivity;
import com.hundsun.yr.universal.p2p.ui.activity.LoginActivity;
import com.hundsun.yr.universal.p2p.ui.activity.ManagementActivity;
import com.hundsun.yr.universal.p2p.ui.activity.MineLoanActivity;
import com.hundsun.yr.universal.p2p.ui.activity.MyWebCreditActivity;
import com.hundsun.yr.universal.p2p.ui.activity.OpenAccountBankActivity;
import com.hundsun.yr.universal.p2p.ui.activity.WebProtocolActivity;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseFragment;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @version V1.0
 * @Title: LoanFragment.java
 * @Description: 借款申请fragment
 * @date 2017-5-1 下午5:02:09
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class LoanFragment extends BaseFragment implements OnClickListener,
        ViewCreatorHelper.UpdateItem<LoanProductBeen>,
        AdapterView.OnItemClickListener,
        InitializeView,
        HSDialog.HSDialogOnItemClickListener {
    //    private HSGallery gallery;
    private TextView tv_viewcredit;
    private List<LoanProductBeen> datas;
    /**
     * 产品名称
     */
    private TextView tv_productName;
    /**
     *
     */
    private LoanHandler mDataHandler;

    /**
     * 下拉刷新
     **/
    private HSSwipeRefreshLayout loan_hsSwipeRefreshLayout;
    /**
     * 这个sp里面存储了是否绑卡等情况
     **/
    private HSSharedPreferences mSharedP;

    /**
     * 借款页面跳转的
     */
    private String LOANFLAG = "LOANFLAG";

    private HSNoScrollListView hnslv_loan_product = null;
    private HolderAdapter<LoanProductBeen> mAdapter;
    private NestedScrollView scrollView_loan = null;
    private String zwgt_data;
    private RequestPresenter mPresenter = null;
    private Bundle bundle;
    private HSDialog borrowDialog = null;
    /**
     * 还款授权
     */
    private HSDialog repDialog = null;
    /**
     * 缴费授权
     */
    private HSDialog payFeeDialog = null;
    private int repayment_max_amt;
    private int repayment_min_amt;
    private int repayment_max_deadline;
    private int repayment_min_deadline;

    @Override
    public void onClick(View v) {
        if (!NetUtils.isNetworkConnected(mContext)) {
            showProgressToDismiss();
            return;
        }

        switch (v.getId()) {
            case R.id.frag_loan_viewcredit:
//			mDataHandler.interactive(mDataHandler, R.string.method_queryCredit,LoanHandler.VIEWCREDIT);
                if (!mSharedP.getBoolean(UserInfo.ISLOGIN)) {//是否登陆
                    readyGo(LoginActivity.class);
                } else {
                    if (!NetUtils.isNetworkConnected(mContext)) {
                        showProgressToDismiss();
                        return;
                    }
                    if (isFastDoubleClick()) {
                        return;
                    }
                    //身份判断
                    String zwgt_data = BaseRequestTool2.getFormatedDateString();
                    JSONObject jsonParams = CommTool.getJSONParams(new JSONObject(), sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);

                    mPresenter.loadingData(TaskConstants.IDENTITY, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.IDENTITY, Constants.EVENT_DATA,
                            jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_user_test) + TaskConstants.IDENTITY, sharedPreferences.getShareProf(UserInfo.USER_NO),
                                    sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
                }
                break;
        }
    }

    @Override
    protected void onFirstUserVisible() {
        refreshUI();
    }

    /**
     * 第一次进来的时候，请求网络刷新一把数据
     */
    private void refreshUI() {
        if (sharedPreferences.getBoolean(UserInfo.ISLOGIN)) {
            // TODO: 2017/4/27 用户已经登陆了，开始加载借款产品数据
            long currentTimeMillis = System.currentTimeMillis();
            mDataHandler.interactive(mDataHandler, R.string.loanProductList, currentTimeMillis);
        } else {
            //用户没有登陆，显示空白数据
            addDatas(new ArrayList<LoanProductBeen>());
        }
    }

    @Override
    protected void onUserVisible() {
        MobclickAgent.onPageStart("LoanFragment");
    }

    @Override
    protected void onUserInvisible() {
        MobclickAgent.onPageEnd("LoanFragment");
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void initViewsAndEvents() {
        findViews();
        mPresenter = new InitializePresenterImpl(mContext, this);
        tv_productName.setText(getString(R.string.tab_loan));

        //初始化标题
        mDataHandler = new LoanHandler(mContext, this);
        mSharedP = new HSSharedPreferences(mContext, SPPath.file_userLoginedInfo);
        tv_viewcredit.setOnClickListener(this);

        loan_hsSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (mDataHandler != null) {
                    refreshUI();
                }
            }
        });

//        loan_hsSwipeRefreshLayout.setEnabled(false);
        /**设置viewpager或者listView时候的一个帮组类**/
        ViewCreatorHelper<LoanProductBeen> creatorHelper = new ViewCreatorHelper<LoanProductBeen>(R.layout.item_loan_product, this);
        mAdapter = new HolderAdapter<LoanProductBeen>(mContext, creatorHelper.viewCreator());

        hnslv_loan_product.setAdapter(mAdapter);
        hnslv_loan_product.setOnItemClickListener(this);

        hnslv_loan_product.setFocusable(false);
        hnslv_loan_product.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                scrollView_loan.scrollTo(0, 0);
            }
        });
        datas = new ArrayList<>();
        mAdapter.update(datas);

        if (ImmersionBar.isSupportStatusBarDarkFont()) { //判断当前设备支不支持状态栏字体变色
            //处理状态栏字体为黑色
            ImmersionBar.with(this).titleBar(R.id.ll_loan_title).statusBarDarkFont(true).flymeOSStatusBarFontColor(R.color.black).init();
        } else {
            //处理状态栏有透明度
            ImmersionBar.with(this).titleBar(R.id.ll_loan_title).statusBarDarkFont(true).transparentStatusBar().init();
        }

    }

    private void findViews() {
        tv_viewcredit = findView(R.id.frag_loan_viewcredit);
        loan_hsSwipeRefreshLayout = findView(R.id.loan_hsSwipeRefreshLayout);
        tv_productName = findView(R.id.loan_product_name);
        hnslv_loan_product = findView(R.id.hnslv_loan_product);
        scrollView_loan = findView(R.id.scrollView_loan);
    }

    /**
     * 装载数据
     *
     * @param datas
     */
    public void addDatas(List<LoanProductBeen> datas) {
        loan_hsSwipeRefreshLayout.setRefreshing(false);
//        scrollView_loan.scrollTo(0,0);
        if (datas == null) {
            return;
        }

        if (datas.isEmpty() || !(datas.get(0) instanceof LoanProductBeen)) {
            //数据为空，或者数据类型不正确，显示默认的布局，可能显示登陆，授信的布局
            if (datas.isEmpty()) {
                datas.add(null);
            }
            this.datas = datas;
            mAdapter.update(datas);
        } else {
            //请求数据成功，数据类型正确，显示网络布局
            this.datas = datas;
            mAdapter.update(datas);
            if (datas.size() == 1) {
                //就一个投资产品
                if (datas != null) {
                    LoanProductBeen dbean = datas.get(0);
                    if (dbean instanceof LoanProductBeen) {
//                        tv_productName.setText(dbean.name);
                    } else {
//                        tv_productName.setText("");
                    }
                }
            } else {
//                tv_productName.setText(datas.get(0).name);
            }
        }

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.frag_loan;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
        if (eventCenter.getEventCode() == Constants.EVENT_REFRESH_DATA) {
            long currentTimeMillis = System.currentTimeMillis();
            mDataHandler.interactive(mDataHandler, R.string.loanProductList, currentTimeMillis);
        } else if (eventCenter.getEventCode() == Constants.EVENT_DATA_LOGIN_EXPIRED2 || eventCenter.getEventCode() == Constants.EVENT_DATA_LOGIN_EXPIRED) {
            addDatas(new ArrayList<LoanProductBeen>());
//            long currentTimeMillis = System.currentTimeMillis();
//            mDataHandler.interactive(mDataHandler, R.string.loanProductList, currentTimeMillis);
        }
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    /**
     * 刷新数据
     *
     * @param view
     * @param position
     * @param dbean
     */
    @SuppressWarnings("deprecation")
    @Override
    public void refreshItem(View view, final int position, final LoanProductBeen dbean) {
        if (dbean == null) {
            LinearLayout ll_have_credit = findView(view, R.id.ll_have_credit);
            ImageView iv_no_credit = findView(view, R.id.iv_no_credit);
            ll_have_credit.setVisibility(View.GONE);
            iv_no_credit.setVisibility(View.VISIBLE);

            final HSButton btn_loan = findView(view, R.id.btn_loan);

            if (sharedPreferences.getBoolean(UserInfo.ISLOGIN)) {
                if (!TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_ACCOUNT), "YES")) {//是否开户
                    btn_loan.setText(getString(R.string.real_open_account));
                    btn_loan.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (isFastDoubleClick()) {
                                return;
                            }

                            readyGo(OpenAccountBankActivity.class);
                        }
                    });
                } else {
                    btn_loan.setText(getString(R.string.apply_credit));
                    //申请授信
                    btn_loan.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (!NetUtils.isNetworkConnected(mContext)) {
                                showProgressToDismiss();
                                return;
                            }

                            if (isFastDoubleClick()) {
                                return;
                            }
                            //身份判断
                            String zwgt_data = BaseRequestTool2.getFormatedDateString();
                            JSONObject jsonParams = CommTool.getJSONParams(new JSONObject(), sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);

                            mPresenter.loadingData(TaskConstants.IDENTITY, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.IDENTITY, Constants.EVENT_DATA,
                                    jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_user_test) + TaskConstants.IDENTITY, sharedPreferences.getShareProf(UserInfo.USER_NO),
                                            sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
                        }
                    });
                }
            } else {
                btn_loan.setText(getString(R.string.login));
                btn_loan.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isFastDoubleClick()) {
                            return;
                        }
                        Bundle bundle = new Bundle();
                        bundle.putString("LOANFLAG", "LOANFLAG");
                        readyGo(LoginActivity.class, bundle);
                    }
                });

            }

        } else if (dbean instanceof LoanProductBeen) {
            LinearLayout ll_have_credit = findView(view, R.id.ll_have_credit);
            ImageView iv_no_credit = findView(view, R.id.iv_no_credit);
            ll_have_credit.setVisibility(View.VISIBLE);
            iv_no_credit.setVisibility(View.GONE);

//            gallery.getViewPager().setReMeasure(true);
            final LoanProductBeen bean = (LoanProductBeen) dbean;
            final HSButton btn_loan = findView(view, R.id.btn_loan);
            /**
             * 产品名字
             */
            TextView tv_loan_product_name = findView(view, R.id.tv_loan_product_name);
            /**
             * 发标审核
             */
            TextView tv_auditing_term = findView(view, R.id.tv_auditing_term);
            /**
             * 最高额度
             */
            TextView tv_max_loan_amount = findView(view, R.id.tv_max_loan_amount);
            /**
             * 还款方式
             */
            TextView tv_paymethod = findView(view, R.id.tv_paymethod);
            /**
             * 最高期限
             */
            TextView tv_max_term = findView(view, R.id.tv_max_term);

            tv_loan_product_name.setText(bean.name);
            tv_auditing_term.setText(getString(R.string.loan_check_period, bean.review_term));
            tv_max_loan_amount.setText(getString(R.string._yuan, CommTool.keep2Digits(Double.valueOf(bean.debt_max) + "")));
            tv_paymethod.setText(bean.getPayMethod(mContext));

            //获取最大借款期限
            String maxBrwPeriod = mContext.getString(R.string._loan_period_day, bean.getTerm());
            tv_max_term.setText(maxBrwPeriod);
            btn_loan.setText(getString(R.string.loan_apply));

            if (MathUtils.compare(datas.get(position).remain_credit, "0") <= 0) {
                btn_loan.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showProgress(getString(R.string.your_credit_no, dbean.name));
                        if (isFastDoubleClick()) {
                            return;
                        }

                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                closeProgress();
                                readyGo(MineLoanActivity.class);
                            }
                        }, 2000);
                    }
                });
            } else {
                /**
                 * 借款申请按钮操作
                 */
                btn_loan.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isFastDoubleClick()) {
                            return;
                        }
                        //请求授权情况接口，然后加入判断
                        zwgt_data = BaseRequestTool2.getFormatedDateString();
                        //授权情况
                        mPresenter.loadingData(TaskConstants.TASK_GETAUTHLIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_GETAUTHBUTTON, Constants.EVENT_REFRESH_DATA,
                                BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.TASK_GETAUTHBUTTON, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.
                                        getShareProf(UserInfo.TOKENID), zwgt_data), false);
                        bundle = new Bundle();
                        bundle.putSerializable(Extras.DATA, datas.get(position));
                    }

                });
            }

        }
    }

    private void showProgressToDismiss() {
        showProgress("");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                closeProgress();
            }
        }, 2000);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 借款申请结果回调
     *
     * @param task_name 任务名称
     * @param data      返回数据
     * @param <T>
     */
    @Override
    public <T> void initializeViews(String task_name, T data) {
        switch (task_name) {
            case TaskConstants.TASK_GETAUTHLIST:
                AuthListBean authListBean = (AuthListBean) data;
                if (authListBean.repay_auth.rst == 0) {
                    repayment_max_amt = authListBean.repay_auth.rule.max_amt.max;
                    repayment_min_amt = authListBean.repay_auth.rule.max_amt.min;
                    repayment_max_deadline = authListBean.repay_auth.rule.deadline.max;
                    repayment_min_deadline = authListBean.repay_auth.rule.deadline.min;
                }
                /**
                 * 4.5 申请借款新增接口
                 */
                HashMap<String, String> hearMap = BaseRequestTool2.getHearder(mContext,
                        TaskConstants.TASK_POST, getString(R.string.api_loan_isauth),
                        sharedPreferences.getShareProf(UserInfo.USER_NO),
                        sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                mPresenter.loadingData(TaskConstants.TASK_NEW_ADD, getString(R.string.root_url_test) + getString(R.string.api_loan_isauth)
                        , 0, new HashMap<String, String>(), hearMap, true);
                break;
            case TaskConstants.TASK_NEW_ADD:
                AdSlideBeen adSlideBeen = (AdSlideBeen) data;
                Log.e("CODECODE", adSlideBeen.toString());
                switch (((AdSlideBeen) data).getCode()) {
                    //未签还款授权
                    case "000001":
                        repDialog = new HSDialog(getString(R.string.tips), ((AdSlideBeen) data).getMsg(), "暂不签约",
                                "立即签约", mContext, this).setCancelable(false);
                        repDialog.show();
                        break;
                    //未签缴费授权
                    case "000002":
                        payFeeDialog = new HSDialog(getString(R.string.tips), ((AdSlideBeen) data).getMsg(), "暂不签约",
                                "立即签约", mContext, this).setCancelable(false);
                        payFeeDialog.show();
                        break;
                    case "000000":
                        readyGo(IWantLoanActivity.class, bundle);
                        break;
                }
                break;
            case TaskConstants.IDENTITY:
                String zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap mHeader = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.h5_user) + TaskConstants.TASK_MYCREDIT,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                HeaderMap headerMap = new HeaderMap();
                headerMap.setMap(mHeader);
                Bundle bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.mine_credit));
                bundle.putString(WebProtocolActivity.PROTOCOL_CODE, EnumProtocol.findCode(EnumProtocol.HELP));
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, getString(R.string.root_h5_url_test) + getString(R.string.h5_user) + TaskConstants.TASK_MYCREDIT);
                bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.HTTP.getIntValue());
                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(MyWebCreditActivity.class, bundle);
                break;
        }
    }

    @Override
    public <T> void initializeError(String task_name, T data) {

    }

    @Override
    public void onItemClick(Object o, int position) {
        if (o == borrowDialog) {
            //缴费授权
        } else if (o == payFeeDialog && position != -1) {
            readyGo(ManagementActivity.class);
            //还款授权
        } else if (o == repDialog && position != -1) {
            readyGo(ManagementActivity.class);
        }
    }

}
